﻿using System.Windows.Forms;
using Nomad.WebSync.Extensions;
using System;
using Nomad.WebSync.Pocket.Sync;
using OpenNETCF.WindowsCE;
using Nomad.WebSync.Pocket.Services;

namespace Nomad.WebSync.Pocket {
    /// <summary>
    /// Form synchronization control
    /// </summary>
    public partial class mainForm : Form {
        private Settings settings;

        /// <summary>
        /// Creates a new instance of mainForm class
        /// </summary>
        public mainForm() {
            InitializeComponent();
        }

        public void LoadSettings() {
            //this.label1.Text = OpenNETCF.WindowsCE.DeviceManagement.GetDeviceGuid().ToString();
            this.settings = new Settings();
        }        

        private void logon() {
            logonPanel.Visible = true;
            Application.DoEvents();
            try {
                using (var service = new WebSyncService.Mobile()) {
                    string sessionId = null;
                    try {
                        sessionId = service.Login(this.settings.Username, this.settings.Password.Encrypt());
                    } catch (Exception ex) {
                        throw new Exception("Connection error...", ex);
                    }

                    if (string.IsNullOrEmpty(sessionId))
                        throw new Exception("Invalid Login");

                    Program.WebSyncHeader = new Nomad.WebSync.Pocket.WebSyncService.WebSyncHeader();
                    Program.WebSyncHeader.Session = sessionId;
                }

                this.verifyDeviceAccess();
            } finally {
                logonPanel.Visible = false;
                Application.DoEvents();
            }
        }
        private void verifyDeviceAccess() {
            using (var service = Mobile.Connect()) {
                var deviceID = service.GetDeviceID();
                if (String.IsNullOrEmpty(deviceID)) {
                    service.SetDeviceID(DeviceManagement.GetDeviceGuid().ToString());
                } else if (deviceID != DeviceManagement.GetDeviceGuid().ToString()) {
                    throw new Exception("Invalid Device");
                }

                OwnerInformation.Synchronize(service);
            }
        }
        private void openConfigForm() {
            using (var config = new configForm()) {
                config.ShowDialog();
            }
        }
        private void applicationExit() {
            Application.Exit();
        }

        private void synchronize() {
            this.logon();
            
            if (this.settings.SyncContacts) this.contactsSynchronization();
            if (this.settings.SyncCalendar) this.appointmentsSynchronization();
            if (this.settings.SyncTasks) this.tasksSynchronization();

            MessageBox.Show("Synchronization Finished!");
            Application.Exit();
        }        

        private void contactsSynchronization() {
            Cursor.Current = Cursors.WaitCursor;
            try {
                Application.DoEvents();
                using (var contacts = new Sync.Contacts()) {
                    contacts.ProgressChanged += new ProgressEventHandler(contacts_ProgressChanged);
                    contacts.Start();
                }
            } finally {
                Cursor.Current = Cursors.Default;
            }
        }
        private void appointmentsSynchronization() {
            Cursor.Current = Cursors.WaitCursor;
            try {
                Application.DoEvents();
                using (var appointments = new Sync.Appointments()) {
                    appointments.ProgressChanged += new ProgressEventHandler(appointments_ProgressChanged);
                    appointments.Start();
                }
            } finally {
                Cursor.Current = Cursors.Default;
            }
        }
        private void tasksSynchronization() {
            Cursor.Current = Cursors.WaitCursor;
            try {
                Application.DoEvents();
                using (var tasks = new Sync.Tasks()) {
                    tasks.ProgressChanged += new ProgressEventHandler(tasks_ProgressChanged);
                    tasks.Start();
                }
            } finally {
                Cursor.Current = Cursors.Default;
            }
        }

        private void contactsSynchronizationProgress(ProgressEventArgs e) {
            this.contactsProgressBar.Minimum = e.Minimum;
            this.contactsProgressBar.Maximum = e.Maximum;
            this.contactsProgressBar.Value = e.Current;
        }        
        private void appointmentsSynchronizationProgress(ProgressEventArgs e) {
            this.calendarProgressBar.Minimum = e.Minimum;
            this.calendarProgressBar.Maximum = e.Maximum;
            this.calendarProgressBar.Value = e.Current;
        }
        private void tasksSynchronizationProgress(ProgressEventArgs e) {
            this.tasksProgressBar.Minimum = e.Minimum;
            this.tasksProgressBar.Maximum = e.Maximum;
            this.tasksProgressBar.Value = e.Current;
        }

        private void contacts_ProgressChanged(object sender, ProgressEventArgs e) {
            try {
                this.contactsSynchronizationProgress(e);
            } catch (System.Exception ex) {
                MessageBox.Show(ex.SoapMessage());
            }
        }
        private void appointments_ProgressChanged(object sender, ProgressEventArgs e) {
            try {
                this.appointmentsSynchronizationProgress(e);
            } catch (System.Exception ex) {
                MessageBox.Show(ex.SoapMessage());
            }
        }
        private void tasks_ProgressChanged(object sender, ProgressEventArgs e) {
            try {
                this.tasksSynchronizationProgress(e);
            } catch (System.Exception ex) {
                MessageBox.Show(ex.SoapMessage());
            }
        }
        private void startMenuItem_Click(object sender, System.EventArgs e) {
            try {
                this.synchronize();
            } catch (System.Exception ex) {
                MessageBox.Show(ex.SoapMessage());
            }
        }
        private void optionsMenuItem_Click(object sender, EventArgs e) {
            try {
                this.openConfigForm();
            } catch (System.Exception ex) {
                MessageBox.Show(ex.SoapMessage());
            }
        }
        private void mainForm_Load(object sender, EventArgs e) {
            try {
                this.LoadSettings();
            } catch (System.Exception ex) {
                MessageBox.Show(ex.SoapMessage());
            }
        }
        private void exitMenuItem_Click(object sender, EventArgs e) {
            try {
                this.applicationExit();
            } catch (System.Exception ex) {
                MessageBox.Show(ex.SoapMessage());
            }
        }
    }
}